package xp2p.adv.jxta;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import net.jxta.document.Advertisement;
import net.jxta.document.Document;
import net.jxta.document.Element;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocument;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.TextElement;
import net.jxta.id.ID;
import net.jxta.id.IDFactory;

public abstract class AdvBase extends Advertisement
{
	public final static String IdTag = "xp2pId";
	public final static String TypeTag = "type";
	
	public HashMap<String, Object> Properties = new HashMap<String, Object>();

		protected void DefineProps()
	{		
		Properties.put(IdTag, null);
		Properties.put(TypeTag, getDocType());
	}

	public AdvBase()
	{
		DefineProps();
	}

	public AdvBase(Element root)
	{
		DefineProps();
		TextElement element = (TextElement) root;
		Enumeration TheElements = element.getChildren();
		while (TheElements.hasMoreElements())
		{
			TextElement TheElement = (TextElement) TheElements.nextElement();
			ProcessElement(TheElement);
		}
	}

	protected Element createElement(StructuredDocument target, String key,
			Object value)
	{
		Element result = target.createElement(key, value);
		target.appendChild(result);
		return result;
	}
	
	protected Element createElement(StructuredDocument target, Element parent, String key, Object value)
	{
		Element result = target.createElement(key, value);
		parent.appendChild(result);
		return result;
	}

	@Override
	public String getAdvType()
	{
		return this.getClass().getName();
	}
	
	public abstract String getDocType();

	public StructuredDocument getStructuredDocument(MimeMediaType arg0)
	{
		StructuredDocument result = StructuredDocumentFactory
				.newStructuredDocument(arg0, getDocType());
		Iterator<String> it = Properties.keySet().iterator();
		while (it.hasNext())
		{
			String key = it.next();
			createElement(result, key, Properties.get(key));
		}		
		return result;
	}
	
	@Override
	public Document getDocument(MimeMediaType arg0)
	{
		return getStructuredDocument(arg0);
	}

	@Override
	public ID getID()
	{
		String value = (String) Properties.get(IdTag);
		if (value == null)
		{
			return null;
		}
		ID id;
		try
		{
			id = IDFactory.fromURI(new URI(value));
			return id;
		} catch (URISyntaxException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String[] getIndexFields()
	{
		return Properties.keySet().toArray(new String[0]);
	}

	protected void ProcessElement(TextElement element)
	{
		String name = element.getName();
		String value = element.getValue();
		Properties.put(name, value);
	}

	public void setID(ID id)
	{
		Properties.put(IdTag, id.toURI().toString());
	}
}
